'use strict'
const router=require('koa-router')()
const fs=require('fs')

function getrouterList(filepath){
    let tmpPath=filepath || __dirname
    let file=fs.readdirSync(tmpPath)
    let filerouter=file.filter(item=>{
        return item.endsWith('.js') && item != 'index.js'
    })
    return filerouter
}

function regisfilerouter(router,filerouter){
    filerouter.forEach(item => {
        let tmpPath=__dirname+'/'+item
        let obj=require(tmpPath)
        for(let key in obj){
            let tmpArr=key.split(' ')
            let routeUrl=tmpArr[1]
            let routeMethod=tmpArr[0]
            let routeFunction=obj[key]
            if(routeMethod==='get'){
                router.get(routeUrl,routeFunction)
            }else if(routeMethod==='post'){
                router.post(routeUrl,routeFunction)
            }else if(routeMethod==='put'){
                router.put(routeUrl,routeFunction)
            }else if(routeMethod==='delete'){
                router.delete(routeUrl,routeFunction)
            }else{

            }
        }
    });
    return router.routes()
}

module.exports=function(){
    let filerouter=getrouterList()
    let fn=regisfilerouter(router,filerouter)
    return fn
}